
const Mock = require('mockjs')
const { list: listCarpool } = require('./carpools')
const { find: findShopMovie } = require('./shop-movie')
const { list: listUser } = require('./user')
const { list: listOrgUnit } = require('./org-units')
const users = listUser(1, 50).data.records
const carpools = listCarpool(1, 50).data.records
const orgUnits = listOrgUnit(1, 50).data.records
const CouponUseRecords = []
let id = 1
for (let i = 0; i < 26; ++i) {
  CouponUseRecords.push(Mock.mock({
    id: id++,
    carpoolTitle: carpools[i % carpools.length].title,
    carpoolMoveName: findShopMovie(carpools[i % carpools.length].id).movieName,
    carpoolStartTime: carpools[i % carpools.length].startTime,
    carpoo1BeginTime: carpools[i % carpools.length].beginTime,
    feeName: '剧本费',
    feeAmount: Mock.Random.integer(0, 50000),
    amount: Mock.Random.integer(0, 2000),
    orgUnitId: orgUnits[i % orgUnits.length].id,
    orgUnitName: orgUnits[i % orgUnits.length].name,
    time: Mock.Random.datetime(),
    confirmTime: Mock.Random.datetime(),
    couponUserNickname: users[i % users.length].nickname,
    couponUserPhoneNumber: users[i % users.length].phoneNumber,
    status: Mock.Random.integer(0, 10)
  }))
}
function list(page, limit, userinfo, orgUnitId, start, end, status) {
  limit = Math.max(1, Math.min(parseInt(limit), 50))
  page = Math.max(parseInt(page), 1)
  orgUnitId = orgUnitId ? parseInt(orgUnitId) : null
  status = status ? parseInt(status) : null
  const startTime = start ? new Date(start) : null
  const endTime = end ? new Date(end) : null
  userinfo = userinfo ? String(userinfo) : null
  let mocks = CouponUseRecords.filter(item => {
    if (orgUnitId && item.orgUnitId !== orgUnitId) return false
    if (status !== null && status !== item.status) return false
    const timeTemp = new Date(item.carpoolStartTime)
    if (startTime && endTime && (timeTemp < startTime || timeTemp > endTime)) return false
    return true
  })
  const likeUserName = mocks.filter(item => {
    if (userinfo && item.couponUserNickname.indexOf(userinfo) === -1) return false
    return true
  })
  const likeUserPhone = mocks.filter(item => {
    if (userinfo && item.couponUserPhoneNumber.indexOf(userinfo) === -1) return false
    return true
  })
  // 去重
  const totalData = likeUserName.concat(likeUserPhone)
  mocks = Array.from(new Set(totalData))
  let total = CouponUseRecords.length
  if (userinfo || orgUnitId || start || end || status !== null) {
    total = mocks.length
  }
  mocks = mocks.filter((u, index) => index < limit * page && index >= limit * (page - 1))
  return { success: true, message: '', data: { total: total, size: limit, current: 1, pages: 1, records: mocks }}
}
module.exports = { list }
